package com.da.lon.wang.xlg.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.UpdateBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.constants.XLGConstants.MethodName;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.JpushUtil;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.ui.main.MainActivity;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LaunchActivity extends BaseActivity {

    public static final String MESSAGE_RECEIVED_ACTION = "com.da.lon.wang.xlg.receiver.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static String webUrl;
    public static boolean isForeground = false;
    private boolean isExit = false;
    private MessageReceiver mMessageReceiver;
    private SharedPreferences mUserInfoSp;
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (isExit) {
                return;
            }
            switch (msg.what) {
                case 1:
                    gotoHome();
                    break;
                case XLGConstants.NETERROR:
                    showNetError(LaunchActivity.this);
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        isForeground = true;
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        isForeground = false;
        JPushInterface.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xlg_launch);
        mUserInfoSp = MyApplication.getInstance().getSharedPreferences("user_info", MODE_PRIVATE);
        MobclickAgent.openActivityDurationTrack(false);

        JPushInterface.init(this);
        init();
        registerMessageReceiver();

        if (isNetworkAvailable()) {
            checkUpdate();
        } else {
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(4000);
                        handler.sendEmptyMessage(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                ;
            }.start();
        }
    }

    private void init() {
        JPushInterface.init(getApplicationContext());
    }

    private void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public boolean isNetworkAvailable() {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private void gotoHome() {

        boolean isFirst = PreferenceUtils.getInstance().getSettingBool(
                "is_first", false);

        if (!isFirst) {
            Intent guideIntent = new Intent(LaunchActivity.this,
                    GuideActivity.class);
            startActivity(guideIntent);
            PreferenceUtils.getInstance().SetSettingBoolean("is_first", true);
        } else {
            Intent intent;
//			if ("".equals(MyApplication.getShopId())) {
//				intent = new Intent(LaunchActivity.this,
//						ChoessSKUListActivity.class);
//			} else {
            intent = new Intent(LaunchActivity.this, MainActivity.class);
//			}
            startActivity(intent);
        }
        finish();
    }

    private void checkUserName() {
        if (TextUtils.isEmpty(mUserInfoSp.getString("user_key", ""))) {
            Disposable disposable = RestAPI.getInstance().oSellService()
                    .autoSignUp()
                    .toObservable()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(userResponseData -> {
                        if (userResponseData != null && TextUtils.equals(userResponseData.code, "000000")) {
                            mUserInfoSp
                                    .edit()
                                    .putBoolean("signed_in", true)
                                    .putString("user_id", userResponseData.data.id)
                                    .putString("user_key", userResponseData.data.userKey)
                                    .apply();
                            PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_KEY, userResponseData.data.userKey);
                            PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_ID, userResponseData.data.id);
                            if (userResponseData.data.storeId != null) {
                                PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.STORE_ID, userResponseData.data.storeId);
                                PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.STORE_NAME, userResponseData.data.storeName);
                            }
                        }
                        handler.sendEmptyMessageDelayed(1, 1 * 1000);
                    }, throwable -> {

                    });
//            handler.sendEmptyMessageDelayed(1, 1000);
        } else {
            autoLogin();
        }
    }

    private void checkUpdate() {

        String url = XLGConstants.URL + XLGConstants.URL_HEAD
                + MethodName.UPDATE;
        HttpLoader<UpdateBean> httpLoader = new HttpLoader<>(this,
                url, UpdateBean.class);
        AjaxParams params = new AjaxParams();
        try {
            final PackageInfo packageInfo = getPackageManager().getPackageInfo(
                    getPackageName(), 0);
            params.put("versionCode", packageInfo.versionCode + "");
            params.put("versioName", packageInfo.versionName);
            params.put("device_type", "1");
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5(XLGConstants.API
                            + XLGConstants.SECRET + MethodName.UPDATE));
            httpLoader.setManagerListener(new OnWebLoadListener<UpdateBean>() {

                @Override
                public void OnStart() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void OnError(String error) {
                    checkUserName();
                }

                @Override
                public void onSuccess(UpdateBean t) {
                    try {
                        if (t != null && t.getCode().equals("000000")) {

                            if (t.getResult().getIsUpgrade() != null && t.getResult().getIsUpgrade().equals("1")) {
                                Intent updataIntent = new Intent(
                                        LaunchActivity.this,
                                        UpdataActivity.class);
                                updataIntent.putExtra("versionCode", t
                                        .getResult().getVersionCode());
                                updataIntent.putExtra("url", t.getResult()
                                        .getUrl());
                                updataIntent.putExtra("isForced", t.getResult()
                                        .getIsForced());
                                updataIntent.putExtra("des", t.getResult()
                                        .getExplain());
                                updataIntent.putExtra("versionName", t
                                        .getResult().getVersionName());
                                MyApplication.addActivity(LaunchActivity.this);
//								startActivity(updataIntent);
                                LaunchActivity.this.startActivityForResult(updataIntent, 2008);
                            } else if (t.getResult().getIsUpgrade() != null && t.getResult().getIsUpgrade().equals("0")) {
                                checkUserName();
                            }

                        } else {
                            checkUserName();
                        }
                    } catch (Exception e) {
                        checkUserName();
                    }

                }
            });
            httpLoader.loadData(params);
        } catch (Exception e) {
            checkUserName();
        }
    }

    /**
     * 自动登录
     */
    private void autoLogin() {
        Disposable disposable = RestAPI.getInstance().oSellService().autoLogin(mUserInfoSp.getString("user_id", ""),
                mUserInfoSp.getString("user_key", ""))
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userResponseData -> {
                    if (userResponseData != null && TextUtils.equals(userResponseData.code, "000000")) {
                        mUserInfoSp
                                .edit()
                                .putBoolean("signed_in", true)
                                .putString("user_id", userResponseData.data.id)
                                .putString("user_key", userResponseData.data.userKey)
                                .apply();
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_KEY, userResponseData.data.userKey);
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_ID, userResponseData.data.id);
                        if (userResponseData.data.storeId != null) {
                            PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.STORE_ID, userResponseData.data.storeId);
                            PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.STORE_NAME, userResponseData.data.storeName);
                        }
                    }
                    handler.sendEmptyMessageDelayed(1, 1 * 1000);
                }, throwable -> showNetError(LaunchActivity.this));
    }

    private void showNetError(Context context) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("网络或者服务器出现问题，请稍后再试！");
        builder.setPositiveButton("退出",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
        builder.setNegativeButton("重试",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        autoLogin();
                    }
                });
        builder.create().show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handler.removeMessages(1);
            isExit = true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            checkUserName();
        } else if (requestCode == 200) {
            finish();
        } else if (requestCode == 2008) {
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        webUrl = null;
        super.onDestroy();

        unregisterReceiver(mMessageReceiver);
    }

    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!JpushUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
            }

        }
    }

}
